/**
 用到的listviewItem 是lnear_books_item.xml
 */
package org.buptsse.ui;

import java.util.LinkedList;

import org.buptsse.entity.AddressLocation;
import org.buptsse.entity.NearbyBookItem;
import org.buptsse.thread.GetLocationThread;
import org.buptsse.thread.GetNearbyBookListThread;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ImageService;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class NearBookAllActivity extends ListActivity implements OnScrollListener,OnClickListener{
	
	ListAdapter listAdapter = new ListAdapter();
	ListView list;
	int visibleItemCount;
	
	int scrollState;
	LinkedList<NearbyBookItem> resultList = new LinkedList<NearbyBookItem>();
	int lastItem;
	int count;
	SharedPreferences preferences = null;
	private String distance=APPConstant.DefaultSearchDistance;
	private AddressLocation location;
	private Button setDistanceButton,backButton,refreshButton,showMapButton;
	private ImageView bookPhotoIV;
	private TextView bookNameTV,priceTV,sellerTV,distanceTV,selltimeTV;
	private EditText distanceET;
	private ProgressDialog pDialog;

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case APPConstant.requireGPS:
				openGPSDialog();
				if(pDialog!=null)
					pDialog.dismiss();
				break;
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				finish();
				if(pDialog!=null)
					pDialog.dismiss();
				break;
			case APPConstant.getCurrentLocationError:
				Toast.makeText(getApplicationContext(), "无法获取当前位置", 1000).show();
				finish();
				if(pDialog!=null)
					pDialog.dismiss();
				break;
			case APPConstant.getCurrentLocationFinish:
				if(pDialog!=null)
					pDialog.dismiss();
				location=(AddressLocation) msg.obj;
				//获取列表
				getNearbyBookList();
				break;
			case APPConstant.getNearbyBookListError:
				Toast.makeText(getApplicationContext(), "没有搜索到相关内容", 1000).show();
				listAdapter.count=0;
				listAdapter.notifyDataSetChanged();
				if(pDialog!=null)
					pDialog.dismiss();
				break;
			case APPConstant.getNearbyBookListFinish:
				resultList=(LinkedList<NearbyBookItem>) msg.obj;
				listAdapter.count=resultList.size();
				listAdapter.notifyDataSetChanged();
				//Toast.makeText(getApplicationContext(), "size is:"+resultList.size(), 1000).show();
				if(pDialog!=null)
					pDialog.dismiss();
				break;
			}
			super.handleMessage(msg);
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lnear_book_all);
		preferences=getSharedPreferences(APPConstant.PROJECT_NAME, MODE_PRIVATE);
		if(preferences.contains("distance")==true)
		{
			distance=preferences.getString("distance", APPConstant.DefaultSearchDistance);
		}
		setDistanceButton=(Button) findViewById(R.id.set_distance_button);
		setDistanceButton.setOnClickListener(this);
		backButton=(Button) findViewById(R.id.rd_back);
		backButton.setOnClickListener(this);
		showMapButton=(Button) findViewById(R.id.rd_show_in_map);
		showMapButton.setOnClickListener(this);
		setListAdapter(listAdapter);
		listAdapter.count=0;
		listAdapter.notifyDataSetChanged();
		GetLocationThread glt = new GetLocationThread(NearBookAllActivity.this, handler, true);
		glt.start();
		ShowWaittingDialog("正在定位...");
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Intent intent=new Intent();
		intent.putExtra("sellid", resultList.get(position).getSellid());
		intent.setClass(NearBookAllActivity.this, OneBookActivity.class);
		startActivity(intent);
	}

	private void getNearbyBookList()
	{
		GetNearbyBookListThread gnblt=new GetNearbyBookListThread(getApplicationContext(), handler, location.getLongtitude(), location.getLatitude(), distance);
		gnblt.start();
		ShowWaittingDialog("正在加载内容...");
	}

	public void ShowWaittingDialog(String msg)
	{
		pDialog=new ProgressDialog(this);
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
	}
	
	private void openGPSDialog() {
		AlertDialog.Builder builder = new Builder(NearBookAllActivity.this);
		builder.setMessage("GPS未打开，现在打开吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
				startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
				GetLocationThread glt = new GetLocationThread(
						NearBookAllActivity.this, handler, true);
				glt.start();
				ShowWaittingDialog("正在定位...");
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				GetLocationThread glt = new GetLocationThread(
						NearBookAllActivity.this, handler, false);
				glt.start();
				dialog.dismiss();
				ShowWaittingDialog("正在定位...");
			}
		});
		builder.create().show();
	}
	
	class ListAdapter extends BaseAdapter {
		int count = 10;
		@Override
		public int getCount() {
			return count;
		}
		@Override
		public Object getItem(int position) {
			return position;
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(NearBookAllActivity.this);
			View view = inflater.inflate(R.layout.lnear_books_item, null);
			bookNameTV=(TextView) view.findViewById(R.id.bookname);
			priceTV=(TextView) view.findViewById(R.id.price);
			sellerTV=(TextView) view.findViewById(R.id.seller);
			distanceTV=(TextView) view.findViewById(R.id.distance);
			selltimeTV=(TextView) view.findViewById(R.id.selltime);
			bookPhotoIV=(ImageView) view.findViewById(R.id.bookphoto);
			NearbyBookItem item=resultList.get(position);
			bookNameTV.setText(item.getBookname());
			priceTV.setText(item.getPrice());
			sellerTV.setText(item.getSeller());
			distanceTV.setText(item.getDistance());
			selltimeTV.setText(item.getSelltime());
			bookPhotoIV.setImageBitmap(ImageService.getImageByUrl(item.getPhoto()));
			return view;
		}
	}
	
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.visibleItemCount = visibleItemCount;
		lastItem = firstVisibleItem + visibleItemCount - 1;
		if (listAdapter.count >= count) {
			list.removeFooterView(view);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		this.scrollState = scrollState;
	}

	private void showSetDistanceDialog()
	{
		distanceET=new EditText(NearBookAllActivity.this);
		distanceET.setText(distance);
		new AlertDialog.Builder(this).setTitle("请输入搜索范围(米)").setIcon(
	     android.R.drawable.ic_dialog_info).setView(
	     distanceET).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String distanceGet=distanceET.getText().toString();
				try {
					Integer.parseInt(distanceGet);
					preferences.edit().putString("distance", distanceGet).commit();
					distance=distanceGet;
					getNearbyBookList();
				} catch (NumberFormatException e) {
					// TODO: handle exception
					Toast.makeText(getApplicationContext(), "请输入整数数值", 1000).show();
				}
			}
		})
	     .setNegativeButton("取消", null).show();
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.set_distance_button:
			showSetDistanceDialog();
			break;
		case R.id.rd_back:
			finish();
			break;
		case R.id.refresh_button:
			getNearbyBookList();
			break;
		case R.id.rd_show_in_map:
			Intent intent=new Intent();
			APPConstant.list=resultList;
			//intent.putExtra("resultList", resultList);
			System.out.println("longtitude:"+location.getLongtitude());
			System.out.println("latitude:"+location.getLatitude());
			intent.putExtra("myLatitude", location.getLatitude());
			intent.putExtra("myLongtitude", location.getLongtitude());
			intent.setClass(NearBookAllActivity.this, ShowInMapActivity.class);
			startActivity(intent);
			break;
		}
	}

}
